package com.cy.wenxinapi.config;


import com.cy.wenxinapi.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {


    @ExceptionHandler(CustomException.class)
    public Result baseExceptionHandler(CustomException exception) {
        return Result.error(exception.getCode(),exception.getMsg());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result HttpMessageNotReadableException(Exception exception, HttpServletRequest request) {
        System.out.println(exception);
        try {
            StringBuilder requestBody = new StringBuilder();

            // 判断请求体是通过 getReader() 还是 getInputStream() 已经被调用过
            if (request.getReader() != null) {
                BufferedReader reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            } else if (request.getInputStream() != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;


    }

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e){
        log.error("执行异常",e);
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception= (MethodArgumentNotValidException) e;
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        } else {
            return "后端执行异常"+e.getMessage();
        }
    }
}
